﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon;

public class NPCSpawn : Photon.MonoBehaviour 
{
	private LifeController lc;
	private NPCController  controller;
	private LowResPositionSync lrps;
	public Vector3 position;
	public float radiusOfAppearance;
	public float spawnTime;
	private PhotonView photView;
	void Awake () 
	{
		position = transform.position;
		lc = GetComponent<LifeController>();
		lrps = GetComponent<LowResPositionSync>();
		controller = GetComponent<NPCController>();
		photView = GetComponent<PhotonView>();
		if (controller != null)
		{
			controller.spawn = this;
		}
	}
	public void OnJoinedRoom()
	{
		if (photView.isMine || (photView.isSceneView && PhotonNetwork.isMasterClient))
		{	
			Respawn();
		}
	}
	public void Die()
	{	
		transform.position = position;
		controller.destination = position;
		StartCoroutine(WaitThenRespawn());
	}
	IEnumerator WaitThenRespawn()
	{
		yield return new WaitForSeconds(spawnTime);
		Respawn();
		
	}
	void Respawn()
	{	
		if (photView.isMine)
		{
			Vector3 offset = Vector3.zero;
			if (radiusOfAppearance>0)
			{
			float theta = Random.Range(0,2*Mathf.PI);
			float r = Random.Range(0,radiusOfAppearance);
			offset = new Vector3(r*Mathf.Cos(theta),0,r*Mathf.Sin(theta));
			}
			transform.position = position + offset;
			Vector3 rotation = transform.eulerAngles;
			rotation.y = Random.Range(0F,360F);
			transform.eulerAngles = rotation;
			if (controller!= null)
			{
				controller.destination = transform.position;
			}
			if (lrps!=null)
			{
				lrps.SendPosition();
			}
			lc.Respawn();
		}
	}
}
